package com.gexiaobao.pigeon.ui.fragment.mine.organization.detail

import android.graphics.BitmapFactory
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initFooter
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.rxui.tablayout.listener.GlideEngine
import com.gexiaobao.pigeon.app.util.MeSandboxFileEngine
import com.gexiaobao.pigeon.app.util.PictureUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentPassSignOrderBinding
import com.gexiaobao.pigeon.ui.adapter.AdapterPassSignOrder
import com.gexiaobao.pigeon.ui.dialog.RxDialogUpLoadProof
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivitySignPassOrderDetail
import com.gexiaobao.pigeon.viewmodel.OrgRaceViewModel
import com.kingja.loadsir.core.LoadService
import com.luck.picture.lib.basic.PictureSelectionModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.language.LanguageConfig
import com.luck.picture.lib.style.PictureSelectorStyle
import com.zs.easy.imgcompress.EasyImgCompress
import com.zs.easy.imgcompress.listener.OnCompressSinglePicListener
import me.hgj.jetpackmvvm.util.LogUtils
import me.hgj.jetpackmvvm.util.startActivity
import java.io.File


/**
 * @Author      : hxw
 * @Date        : 2024/7/18 10:12
 * @Describe    : 订单（关塞报名）
 */
class FragmentPassSignOrder : BaseFragment<OrgRaceViewModel, FragmentPassSignOrderBinding>() {

    private var proofFile: File? = null
    private var dialog: RxDialogUpLoadProof? = null
    private var orderStatus: Int = 0
    private var raceId = 0
    private lateinit var loadsir: LoadService<Any>
    private val mAdapter: AdapterPassSignOrder by lazy { AdapterPassSignOrder(arrayListOf()) }

    override fun initView(savedInstanceState: Bundle?) {
        raceId = requireArguments().getInt("raceId", 0)
        orderStatus = requireArguments().getInt("orderStatus", 0)

        mDatabind.includeList.swipeRecyclerView.init(LinearLayoutManager(context), mAdapter).let {
            it.addItemDecoration(SpaceItemDecoration(0, Util.dp2px(context, 15f)))
            it.initFooter {
                //触发加载更多时请求数据
                mViewModel.getAppRaceOrderList(false, raceId.toString(), orderStatus)
            }
        }

        mDatabind.includeList.swipeRefreshLayout.init {
            onRefresh()
        }

        //状态页配置
        loadsir = loadServiceInit(mDatabind.includeList.swipeRefreshLayout) {
            //点击重试时触发的操作
            onRefresh()
        }

        onRefresh()

        mAdapter.addChildClickViewIds(R.id.tvItemPassSignSubmitProof)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.tvItemPassSignSubmitProof -> {
                    val orderId = mAdapter.data[position].orderId
                    showDialogProof(orderId)
                }
            }
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            startActivity<ActivitySignPassOrderDetail>("orderId" to mAdapter.data[position].orderId)
        }
    }

    private fun showDialogProof(orderId: Int) {
        dialog = RxDialogUpLoadProof(context)
        dialog!!.setIvListener {
            showPop()
        }
        dialog!!.setSureListener {
            showLoading(getString(R.string.loading))
            proofFile?.let { it1 -> mViewModel.uploadPayFile(orderId, it1) }
        }
        dialog!!.setFullScreenWidth()
        dialog!!.show()
    }

    private fun showPop() {
        val selectionModel: PictureSelectionModel = PictureSelector.create(context)
            .openGallery(SelectMimeType.ofImage())
            .setSelectorUIStyle(PictureSelectorStyle())
            .setImageEngine(GlideEngine.createGlideEngine())
            .setCompressEngine(PictureUtil.getCompressFileEngine())
            .setSandboxFileEngine(MeSandboxFileEngine())
            .setSelectionMode(SelectModeConfig.SINGLE)
            .setCameraInterceptListener(PictureUtil.getCustomCameraEvent())
            .setPermissionDescriptionListener(PictureUtil.getPermissionDescriptionListener())
            .setPreviewInterceptListener(PictureUtil.getPreviewInterceptListener())
            .setPermissionDeniedListener(PictureUtil.getPermissionDeniedListener())
            .setQueryFilterListener { false }
            .isLoopAutoVideoPlay(false)
            .isPageSyncAlbumCount(true)
            .setLanguage(LanguageConfig.SYSTEM_LANGUAGE)
            .setQuerySortOrder("")
            .isDisplayCamera(true)
            .isOpenClickSound(true)
            .isPreviewImage(true)
            .isMaxSelectEnabledMask(true)
            .isDirectReturnSingle(true)
        selectionModel.forResult(object : OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: ArrayList<LocalMedia>?) {
                if (!result.isNullOrEmpty()) {
                    // 把单张图片压缩到1024k以内 同时像素不超过1200（宽、高都不大于1200）
                    EasyImgCompress.withSinglePic(context, result[0].realPath)
                        .maxPx(1200)
                        .maxSize(1024)
                        .enableLog(true)
                        .setOnCompressSinglePicListener(object : OnCompressSinglePicListener {
                            override fun onStart() {
                                LogUtils.debugInfo("onStart")
                            }

                            override fun onSuccess(file: File) {
                                proofFile = file
                                if (proofFile!!.exists() && proofFile!!.isFile) {
                                    val bitmap = BitmapFactory.decodeFile(proofFile?.absolutePath)
                                    dialog?.setImage(bitmap)
                                } else {
                                    RxToast.showToast(getString(R.string.pic_upload_fail))
                                }
                            }

                            override fun onError(error: String) {
                                LogUtils.debugInfo("onError error = $error")
                            }
                        }).start()
                }
            }

            override fun onCancel() {}
        })
    }

    private fun onRefresh() {
        loadsir.showLoading()
        mViewModel.getAppRaceOrderList(true, raceId.toString(), orderStatus)
    }

    override fun createObserver() {
        super.createObserver()
        /** 上传缴费凭证(关塞报名)  */
        mViewModel.uploadPayResult.observe(viewLifecycleOwner) {
            dialog?.dismiss()
            onRefresh()
        }
        /** 获获取比赛的app订单列表 */
        mViewModel.appRaceOrderResult.observe(viewLifecycleOwner) {
            loadListData(it, mAdapter, loadsir, mDatabind.includeList.swipeRecyclerView, mDatabind.includeList.swipeRefreshLayout)
        }
    }

    companion object {
        fun newInstance(raceId: Int, orderStatus: Int): FragmentPassSignOrder {
            val fragment = FragmentPassSignOrder()
            val bundle = Bundle()
            bundle.putInt("raceId", raceId)
            bundle.putInt("orderStatus", orderStatus)
            fragment.arguments = bundle
            return fragment
        }
    }
}